define(["jquery","bbcare","scprit/followup/app/comm/pageTab.js",
	"scprit/followup/app/question/question.servers.js",
	"scprit/followup/app/datatable/datatable.servers.js",
    "scprit/followup/app/datatable/datatable.ui.js"],
    function($,$bb,$pageTab,$questionServers,$datatableServers,$datatableUi){
	var servers = {};

	var URL = $bb.baseUrl("followup");
	var URL2 = $bb.baseUrl("imgCollection");
	var sessinonUserName = JSON.parse($bb.getSessionStorage("account")).alias;
	var  userIdgzyk = "";
	var  patientName = "";

    /**
     * 获取配置数据库时的参数 队列id
     */
    var getPageParams = function(){
        return $bb.getPageParams();
    }
    servers.getPageParams = getPageParams;

    /**
     * 请求患者基本信息
     */
    servers.ajaxPatientInfo = function(params,callback){
    	$bb.ajax({
			url: URL + "followup/service/patient/patientInfoQueryByPtId",
			data:JSON.stringify({
				data : {
					"patientId":params.patientId,
					"ptSchemeId":params.ptSchemeId
				}
			}),
			success: function(data){
				if(data.success){ 
					callback(data.data,params);
				}else{
					$bb.toastShow(data.msg ? data.msg : "请求患者基本信息出错！");
				}
			}
		});
    }

    /**
     * 请求当前专病的任务内容（根据队列id查询）
     */
    servers.ajaxSpecialTask = function(params,callback){
    	var ptSchemeId;
    	if(params.ptSchemeId) ptSchemeId = params.ptSchemeId;
		$bb.ajax({
			url: URL + "followup/service/treat/listSpecialDiseaseTask",
			data:JSON.stringify({
				data : {
					"followQueueId":params.followQueueId,
					"schemeBusiType":1,
					"ptSchemeId":ptSchemeId  // 可空，建档查询出患者之后传该字段
				}
			}),
			success: function(data){
				if(data.success){ 
					callback(data.data,params);
				}else{
					$bb.toastShow(data.msg ? data.msg : "查询当前专病的任务内容出错！");
				}
			}
		});
	}

	/**
	 * 处理获取到的诊疗任务（详细） // 可以删掉了（同pageTab.js）
	 */
	var createObj = function(object,i,curIndex,clickable){
		var obj = {};
		obj.name = object.task_name;
		obj.taskId = object.task_id;
		obj.seq_no = object.seq_no;
		obj.active = i == curIndex ? true : false;
		obj.clickable = clickable;
		return obj;
	};

	/**
	 * 处理获取到的诊疗任务数据  // pageTab.js可以删掉了
	 */
	servers.handleSpecialTask = function(options){
		var data = {};
		if( options.data.length > 0 ){
			var arr = [];
			if( options.data.length > 1 ){
				for (var i = 1; i < options.data.length; i++) {
					arr.push( options.data[i] );
				}
			}
			var data = {
				archive:options.data[0],
				list:arr,
				patientName:options.patientName
			}
		}
		return data;
	}

    /**
	 * 建档保存时，获取schemeList数据
	 */
	var getDataSchemeList = function(domId){
		var arr = [];
		var selectDom = $("#"+ domId +" .qaCard select");
		var pDom = $("#"+ domId +" .qaCard p.form-control-static");
		for (var i = 0; i < selectDom.length; i++) {
			var obj = {};
			var name = selectDom.eq(i).attr("name");
			obj.schemeId = $("#"+ domId +" .qaCard select[name='" + name + "']").val();
			obj.schemeBusiType = Number(name.replace(/scheme-/, ""));
			arr.push(obj);
		}
		for (var i = 0; i < pDom.length; i++) {
			var obj = {};
			var name = pDom.eq(i).attr("name");
			obj.schemeId = $("#"+ domId +" .qaCard p.form-control-static[name='" + name + "']").attr("value");
			obj.schemeBusiType = Number(name.replace(/scheme-/, ""));
			arr.push(obj);
		}
		return arr;
	}

    /**
	 * 获取建档保存参数
	 */
	var getArchiveParams = function(followQueueId){
		var queueName = $("#specialNurseQueueName").attr("queueName");
		var patientName = $("#specialNurseArchive form").find("input[name='Pub1100002']").val();
        var formId = $("#specialNurseArchive form").attr("id");
        var questiones = $questionServers.getDataForDom(formId);
        var schemeList = getDataSchemeList("specialNurseScheme");
        var params = {
			"followQueueId": followQueueId,
			"opCode": "1000",
			"opType": "2",
			"sourceType":"2",
			"userType": "1",
			"opNote": "【"+sessinonUserName + "】医生添加患者【" + patientName + "】建档信息，加入队列" + queueName,
			"questiones": questiones,
			"schemeList": schemeList
		}
		return params;
	}

	/**
	 * 建档保存
	 */
	servers.ajaxPatientAddNew = function(params,callback){
		var patientAddNewParams = getArchiveParams(params.followQueueId);
		$bb.ajax({
			url: URL + "followup/service/treat/patientAddNew",
			data:JSON.stringify({
				data : patientAddNewParams
			}),
			success: function(data){
				if(data.success){
					$bb.toastShow("建档成功！");
					callback(params,data.data);
				}else{
					$bb.toastShow(data.msg ? data.msg : "建档出错！");
				}
			}
		});
	}

	/**
	 * 查询今日门诊记录，查询redis获取
	 */
	servers.ajaxOperateListRedis = function(params,callback){
		$bb.ajax({
			url: URL + "followup/service/treat/patientOperateListRedis",
			data:JSON.stringify({
				data : {
					"flag":"0",
					"schemeBusiType":1,
					"qryType":1,
					"rows":16,
				    "queueId":params.followQueueId,				
				}
			}),
			success: function(data){
				if(data.success){
					callback(data.data,params);
				}else{
					$bb.toastShow(data.msg ? data.msg : "查询今日门诊记录出错！");
				}
			}
		});
	}

	/**
	 * 今日门诊记录
	 */
	servers.rightOutpatientRecords = function(options){
		options.show = options.list.length == 0 ? false : true;
		return options;
	}

	/**
	 * 查询队列下关联的多个方案，建档时供医生选择
	 */
	servers.ajaxQueueScheme = function(params,callback){
		$bb.ajax({
			url: URL + "followup/service/treat/listQueueScheme",
			data:JSON.stringify({
				data : {
					"followQueueId":params.followQueueId,
				}
			}),
			success: function(data){
				if(data.success){
					callback(data.data,params);
				}else{
					$bb.toastShow(data.msg ? data.msg : "查询队列方案出错！");
				}
			}
		});
	}

	/**
	 * 处理获取到的方案
	 */
	servers.handleScheme = function(options){
		var arr = [];
		for (var i = 0; i < options.list.length; i++) {
			arr[i] = options.list[i]; 
			arr[i].name = "scheme-" + arr[i].schemeBusiType;
			if( arr[i].schemeBusiType == "0" ){
				arr[i].schemeBusiName = "随访方案";
			}else if(arr[i].schemeBusiType == "1"){
				arr[i].schemeBusiName = "诊疗方案";
			}
			arr[i].val = options.values ? options.values[0].schemeId : arr[i].rows[0].schemeId;
			arr[i].status = arr[i].rows.length == 1 ? "readonly" : options.status;
		}
		var data = {
			"list":arr,
			"queueName":options.queueName
		};
		return data;
	}

	/**
	 * 请求门诊任务历史记录
	 */
	servers.ajaxHistoryList = function(params,callback){
		$bb.ajax({
			url: URL + "followup/service/treat/qryOprationHistoryList",
			data:JSON.stringify({
				data : {
					"schemeBusiType":"1",
				    "userId":params.patientId,
				    "ptSchemeId":params.ptSchemeId,
				    "queueId":params.followQueueId
				}
			}),
			success: function(data){
				if(data.success){ 
					callback(data.data,params);
				}else{
					$bb.toastShow(data.msg ? data.msg : "请求门诊任务历史记录出错！");
				}
			}
		});
	}

	/**
	 * 获取建档的ptTaskId
	 */
	servers.getArchivePtTaskId = function(rows){
		for (var i = 0; i < rows.length; i++) {
			for (var j = 0; j < rows[i].yearList.length; j++) {
				if( !rows[i].yearList[j].taskId ){
					return rows[i].yearList[j].dateList[0].id;
				}
			}
		}
	}

	/**
	 * 处理门诊诊疗任务右侧数据
	 */
	servers.handleRight = function(data,ptTaskId){
		for (var i = 0; i < data.rows.length; i++) {
			for(var j = 0; j < data.rows[i].yearList.length; j++){
				var str = data.rows[i].yearList[j].finishDate.substr(5,2);
				str = str < 10 ? str.substr(1,1): str;
				data.rows[i].yearList[j].month = str + '月';
				data.rows[i].yearList[j].day = data.rows[i].yearList[j].finishDate.substr(8,2);
				data.rows[i].yearList[j].seqNo = data.rows[i].yearList[j].dateList[0].seqNo;
				for (var k = 0; k < data.rows[i].yearList[j].dateList.length; k++) {
					data.rows[i].yearList[j].dateList[k].active = false;
					if(ptTaskId && ptTaskId == data.rows[i].yearList[j].dateList[k].id){
						data.rows[i].yearList[j].active = true;
					}
				}
			}
		}
		return data;
	}

	/**
	 * 门诊任务详情
	 */
	servers.ajaxOprationHisResource = function(params,callback){
		$bb.ajax({
			url: URL + "followup/service/treat/qryOprationHisResource",
			data:JSON.stringify({
				data : {
					"ptTask":params.ptTaskId,
				    "schemeBusiType":"1",
				    "userId":params.patientId,
				}
			}),
			success: function(data){
				if(data.success){ 
					callback(data.data,params);
				}else{
					$bb.toastShow(data.msg ? data.msg : "请求门诊任务详情出错！");
				}
			}
		});
	}

	/**
	 * 获得门诊任务提交的参数
	 */
	var getTaskParams = function(params){
		var ptTaskId = params.ptTaskId ? params.ptTaskId : "";
		var formId = $("#specialNurseContent form").attr("id");
        var questiones = $questionServers.getDataForDom(formId);
		var params = {
			"oprInfo":{
		        "opCode":"1001",
		        "opNote":"【"+ sessinonUserName + "】医生为【" + params.patientName + "】患者进行门诊诊疗录入",	
		        "opType":"2",
		        "schemeBusiType":"1",
		        "followQueueId":params.followQueueId,
		        "patientId":params.patientId,
		        "ptSchemeId":params.ptSchemeId,
			},
		    "questiones":questiones,
		    "task":{
		        "ptTaskId":ptTaskId,
		        "taskId":params.taskid,
		    }
		};
		return params;
	}

	/**
	 * 门诊任务提交
	 */
	servers.ajaxSubmitTask = function(params,callback){
		var submitTaskparams = getTaskParams(params);
		var flag = $questionServers.isAllEmptyQuestValue(submitTaskparams.questiones);
		if( flag == true ){ // 全为空
			$bb.toastShow("请至少填一项再保存！");
		}else{
			$bb.ajax({
				url: URL + "followup/service/treat/submitTaskFunciton",
				data:JSON.stringify({
					data : submitTaskparams
				}),
				success: function(data){
					if(data.success){ 
						$bb.toastShow("诊疗记录保存成功！");
						callback(data.data,params);
					}else{
						$bb.toastShow(data.msg ? data.msg : "诊疗记录保存出错！");
					}
				}
			});
		}
	}

	/**
	 * 查询队列建档问卷内容
	 */
	servers.ajaxQueueArchiveContent = function(params,callback,req){
		$bb.ajax({
			url: URL + "followup/service/treat/qryQueueArchiveContent",
			data:JSON.stringify({
				data : {
					"followQueueId":params.followQueueId,
					"ptSchemeId":params.ptSchemeId
				}
			}),
			success: function(data){
				if(data.success){
					callback(data.data,params,req);
				}else{
					$bb.toastShow(data.msg ? data.msg : "查询队列建档问卷内容出错！");
				}
			}
		});
	}

	/**
	 * 请求任务模板
	 */
	servers.ajaxTaskContent = function(params,callback){
		$bb.ajax({
			url: URL + "followup/service/treat/qryTaskContent",
			data:JSON.stringify({
				data : {
					"schemeBusiType":"1",
				    "taskId":params.taskid,
				    "followQueueId":params.followQueueId,
				    "ptSchemeId":params.ptSchemeId
				}
			}),
			success: function(data){
				if(data.success){
					callback(data.data,params);
				}else{
					$bb.toastShow(data.msg ? data.msg : "请求任务模板出错！");
				}
			}
		});
	}

	/**
	 * 获得修改建档的参数
	 */
	var getModifyArchiveParams = function(data){
		var patientName = $("#specialNurseArchive form").find("input[name='Pub1100002']").val();
        var formId = $("#specialNurseArchive form").attr("id");
        var questiones = $questionServers.getDataForDom(formId);
		var params = {
			"oprInfo":{
				"followQueueId":data.followQueueId,
		        "opCode":"1001",
		        "opNote":"【"+ sessinonUserName + "】医生修改患者【" + patientName + "】建档信息",	
		        "opType":"2",
		        "patientId":data.patientId,
		        "ptSchemeId":data.ptSchemeId,	
			},
		    "questions":questiones,
		    "taskInfo":{
		    	"ptTaskId":data.ptTaskId,
		        "updateAuname":sessinonUserName,
		    }
		}
		return params;
	}

	/**
	 * 修改建档
	 */
	servers.ajaxModifyArchives = function(params,callback){
		var modifyArchivesParams = getModifyArchiveParams(params);
		$bb.ajax({
			url: URL + "followup/service/treat/modifyPatientArchives",
			data:JSON.stringify({
				data : modifyArchivesParams
			}),
			success: function(data){
				if(data.success){ 
					$bb.toastShow("修改建档信息成功！");
					callback(params);
				}else{
					$bb.toastShow(data.msg ? data.msg : "修改建档信息出错！");
				}
			}
		});
	}

	/******************** begin 南方医院添加 上传资料 ********************/
	/**
     * 上传多文件
     */
    servers.uploadMultiFiles = function(fd,callback){
        $bb.ajax({
            url: URL2 + "imgCollection/uploadFile",
            processData: false,  // 告诉jQuery不要去处理发送的数据
            contentType: false,   // 告诉jQuery不要去设置Content-Type请求头
            data: fd,
            success: function(data){
                if(data.success){
                    callback(data.data);
                }else{
                    $bb.toastShow(data.msg ? data.msg :"上传文件失败！");
                }
            }
        });
    };

    /**
     * 根据文件的一个地址请求文件的另一个地址
     */
    var ajaxImgFileSignUrl = function(params,callback,obj){
    	$bb.ajax({
			url: URL2 + "imgCollection/imgMark/getImgFileSignUrl",
			data:JSON.stringify({
				data : params
			}),
			success: function(data){
				if(data.success){ 
					callback(data.data,obj);
				}else{
					$bb.toastShow(data.msg ? data.msg : "请求文件地址出错！");
				}
			}
		});
    }

    var default_datatable = {}; // datatable入参需要用到的参数，已这种形式才能放进去

    /**
     * 入参
     */
    var inParams = function(args){
    	var data2 = $.extend({},{"args": JSON.stringify(args)},default_datatable);
    	var data = JSON.stringify({
            data: data2
        });
        return data;
    }
    
    /**
     * 出参
     */
    var outParams = function(data){
        return data.rows;
    }
    /**
     * columns
     */
    var columnsData = function(){
        var columnsArr = [
            {
            	"data":"fileAuthorName",
            	"className":"file-name"
            },
            {"data":"updateTime"},
            {"data":"updateAuthor"},
            {
                "data":null,
                "className":"file-down"
            }
        ];
        return columnsArr;
    }
    /**
     * 根据文件的一个地址请求另一个地址成功后的回调函数
     */
    var ajaxImgFileSignUrlCallBack = function(data,obj){
    	var h = '<a href="'+ data.fileList[0].imgNewUrl +'">下载</a>';
    	obj.html(h);
    	var fileObj = window.open(data.fileList[0].imgNewUrl,"_self");
        fileObj.document.execCommand('SaveAs');
    }
    /**
     * 行绘制回调函数
     */
    var rowCallback = function(row, data, index) {
        var html = '<div class="btn-look">下载</div>';
        $('td.file-down', row).html(html);
        $("td.file-down .btn-look",row).unbind("click");
        $("td.file-down .btn-look",row).click(function(){
        	var dom = $(this).find("a");
        	if( dom.length == 0 ){
        		var params = {
			        "channel": "BBCARE-APP",
			        "fileList": [
			            {
			            	"imgUrl":data.filePath,
			            	"imgId":"nfyy"
			            }
			        ]
			    };
	        	ajaxImgFileSignUrl(params,ajaxImgFileSignUrlCallBack,$(this));
        	}
        });
    };
    /**
     * 初始化完成之后的回调函数
     */
    var initComplete = function(setting,json){
        $("#pastFiles").prev("div.row").remove();
    }

	servers.getOptions = function(params){
		var sessionId = $bb.getSessionStorage("sessionId");
		default_datatable = {};
		$.extend(default_datatable,params);
        var options = {
            "ajax": {
                "url": URL2 + "imgCollection/imgMark/queryNffyyFile?sessionId=" + sessionId,
                "data": inParams,
                "dataSrc": outParams
            },
            "columns": columnsData(),
            "rowCallback": rowCallback,
            "initComplete": initComplete,
        };
        return options;
	}

	/********************  end 南方医院添加 上传资料  ********************/



	/******************** begin 眼科绑定图片展示 ********************/

    

    /**
     * 根据文件的一个地址请求另一个地址成功后的回调函数
     */
    var ajaxImgPictureSignUrlCallBack = function(data,obj){
    	/*var h = '<a href="'+ data.fileList[0].imgNewUrl +'">预览</a>';
    	obj.html(h);
    	var fileObj = window.open(data.fileList[0].imgNewUrl,"_self");
        fileObj.document.execCommand('SaveAs');*/
        var className = "modal_picture";
        $bb.modal({
        	"tit":"图片预览",
        	"className":className,
        },function(){
        	var h = "<div class='picInfo'> <img class='picInfo' src ="+data.fileList[0].imgNewUrl+"></div>";
        	$("."+className+" .modal-body").html(h);
        	$("."+className).modal("show");
        })
    }
    /**
     * 行绘制回调函数
     */
    var rowCallbackPicture = function(row, data, index) {
        var html = '<div class="btn-look">预览</div>';
        $('td.file-down', row).html(html);
        $("td.file-down .btn-look",row).unbind("click");
        $("td.file-down .btn-look",row).click(function(){
        	var dom = $(this).find("a");
        	if( dom.length == 0 ){
        		var params = {
			        "channel": "BBCARE-APP",
			        "fileList": [
			            {
			            	"imgUrl":data.filePath,
			            	"imgId":"gzyk"
			            }
			        ]
			    };
	        	ajaxImgFileSignUrl(params,ajaxImgPictureSignUrlCallBack,$(this));
        	}
        });
    };


/**
	 *  绑定
	 */
	var bindFilesCallBack = function(data){
		$bb.toastShow("绑定成功！");
		$datatableUi.table.api().ajax.reload();  // 出发dt的重新加载数据的方法
	}


/**
     * 根据文件的一个地址请求文件的另一个地址
     */
    var ajaxImgBind = function(params,callback,obj){
    	$bb.ajax({
			url: URL2 + "imgCollection/imgMark/addAssImgUser",
			data:JSON.stringify({
				data : params
			}),
			success: function(data){
				if(data.success){ 
					callback(data);
				}else{
					$bb.toastShow(data.msg ? data.msg : "关联图片出错！");
				}
			}
		});
    }



  /**
     * 行绘制回调函数
     */
    var rowCallbackPictureBind = function(row, data, index) {
    	var imgList = [];
        var html = '<div class="btn-look">预览</div><div class="btn-bind">绑定</div>';
        $('td.file-down', row).html(html);
        $("td.file-down .btn-look",row).unbind("click");
        $("td.file-down .btn-bind",row).unbind("click");
        $("td.file-down .btn-look",row).click(function(){
        	var dom = $(this).find("a");
        	if( dom.length == 0 ){
        		var params = {
			        "channel": "BBCARE-APP",
			        "fileList": [
			            {
			            	"imgUrl":data.filePath,
			            	"imgId":"gzyk"
			            }
			        ]
			    };
	        	ajaxImgFileSignUrl(params,ajaxImgPictureSignUrlCallBack,$(this));
        	}
        });

         $("td.file-down .btn-bind",row).click(function(){
         	imgList [0] = data.id;
        	var dom = $(this).find("a");
        	if( dom.length == 0 ){
        		var params = {
					"oprInfo":{
						"opCode":"1116", //1116图片关联具体患者
						"opNote":"【"+sessinonUserName+"】医生给【"+patientName+"】患者关联了【"+ data.sourceFileName +"】图片",
						"opType":"2" //2门诊；
					},
					"assInfo":{
						"imgIdList":imgList, //文件的id列表；
						"userId":userIdgzyk
					}
			    };
	        	ajaxImgBind(params,bindFilesCallBack,$(this));
        	}
        });

    };

	servers.getPicOptions = function(params){
		var bindFlag = params.bindFlag
		userIdgzyk = params.userId;
		patientName = params.patientName;
		//删除属性
		delete params.patientName;
		var functionInfo;
		if(bindFlag){
			delete params.userId;
			functionInfo = rowCallbackPictureBind;
		}else {
			functionInfo = rowCallbackPicture;
		}
		var sessionId = $bb.getSessionStorage("sessionId");
		default_datatable = {};
		$.extend(default_datatable,params);
        var options = {
            "ajax": {
                "url": URL2 + "imgCollection/imgMark/queryNffyyFile?sessionId=" + sessionId,
                "data": inParams,
                "dataSrc": outParams
            },
            "columns": columnsData(),
            "rowCallback": functionInfo,
            "initComplete": initComplete,
        };
        return options;
	}



	/********************  end 南方医院添加 上传资料  ********************/

    return servers;
});
